package com.elysia.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.elysia.common.to.es.SkuEsModel;
import com.elysia.gulimall.search.config.GulimallElasticSearchConfig;
import com.elysia.gulimall.search.constant.EsConstant;
import com.elysia.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient esRestClient;
    @Override
    public boolean saveProductToEs(List<SkuEsModel> skuEsModels) throws IOException {
        //bulk 批量操作
        BulkRequest bulkRequest=new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //保存在哪个index下
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //设置id
            indexRequest.id(skuEsModel.getSkuId().toString());
            //将sku的检索信息 转为 json
            String skuJson= JSON.toJSONString(skuEsModel);
            //设置数据元 并指定 数据源格式
            indexRequest.source(skuJson, XContentType.JSON);
            //将 索引请求 加入到 bulk中
            bulkRequest.add(indexRequest);
        }
        //执行 bulk
        BulkResponse bulkResponse = esRestClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        boolean hasFailure = bulkResponse.hasFailures();
        List<String> collect = Arrays.stream(bulkResponse.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        if(hasFailure){
            log.error("sku商品保存至es失败，失败skuId:{}",collect);
        }

        return ! hasFailure;
    }
}
